package com.health;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.health.adapter.MainMenuGridAdapter_Tj_JTYS;
import com.health.db.FDbManager;
import com.health.focusgroup.GXYActivity;
import com.health.focusgroup.TNBActivity;
import com.health.model.PeopleType;
import com.health.activity.qyinfo.QianMingActivity;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.BD_DD_INFO;
import com.health.tools.GlobalConts;
import com.health.tools.ImageTools;
import com.health.tools.PopData;
import com.health.tools.SPUtil;
import com.health.widget.LabelsView;
import com.novabluetooth.views.SBCLActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 主界面【体检】
 *
 * @author nova
 */
public class MainActivity_Menu_Tj extends NovaActivity implements OnClickListener {

    private static final String TAG = "MainActivity_Menu_Tj";
    private GridView gd_menu;
    private MainMenuGridAdapter_Tj_JTYS menuAdapter;

    private TextView tv_name;

    private ARCHIVE_BASEINFO userinfo = null;
    private long exitTime = 0;
    private ImageView img_back;
    // public static Intent service;
    private Button btn_jktj;// 健康体检

    TextView jtys_list_name;// 姓名
    ImageView jtys_list_img;// 头像
    TextView jtys_list_age;// 年龄
    TextView jtys_jdys_name;// 建档医生姓名
    TextView jtys_list_sex;
    TextView jtys_list_phone;// 手机号
    LabelsView jtys_list_zdrq; // 重点人群
    LabelsView jtys_list_sfry; // 随访提醒
    TextView jtys_list_address;// 地址
//    ImageView jtys_list_state_sign;// 签约状态
//    ImageView jtys_list_state_unsign;// 签约状态

    private FDbManager fdbmanger = null;
    private LinearLayout ll_wxsf;
    Button qianMing;//签名 // 患者
    private final int REQUEST_CODE_PATIENT = 11;
    // 患者签名
    private String strPatientSignPath = "";
    private ImageView img_patientsign;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jmtj_main);
        userinfo = NovaApplication.getUserInfo();
        findViews();
        setListeners();
        if (NovaApplication.idCardTool != null) {
            NovaApplication.idCardTool.stopScanReceive();
        }
        // BloothTool bloothTool = BloothTool.getInstance(this);
        // bloothTool.scanLeDevice(true);
        // NovaApplication.bloothTool = bloothTool;
        setData();

    }

    private void setData() {
        try {
            jtys_list_name.setText(userinfo.getCUSTOMERNAME());
            int age = GlobalConts.getAge(userinfo.getBIRTHDAY());
            if (age != -1) {
                jtys_list_age.setText(String.valueOf(age) + "岁");
            } else {
                jtys_list_age.setText("");
            }

            List<BD_DD_INFO> bdxingbie = FDbManager.getInstance(getApplicationContext())
                    .findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID = 'DM01-08'");
            String sex = "";
            for (BD_DD_INFO bdi : bdxingbie) {
                if (userinfo.getSEX().equals(bdi.getID())) {
                    sex = bdi.getDATAINFO();
                }
            }
            jtys_list_sex.setText(sex);
            jtys_jdys_name.setText("建档医生："+SPUtil.getstr_jdr(mContext));
            if ("女".equals(sex)) {
                jtys_list_img.setImageResource(R.drawable.head_youth_y);
            } else {
                jtys_list_img.setImageResource(R.drawable.head_youth_x);
            }
            jtys_list_phone.setText(userinfo.getPHONE());
            jtys_list_address.setText(userinfo.getHOUSEHOLD_ADDR());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void findViews() {
        try {
            gd_menu = (GridView) findViewById(R.id.gd_menu);
            tv_name = (TextView) findViewById(R.id.tv_name);
            if (userinfo != null) {
                int i = userinfo.getCUSTOMERNAME().length() + 7;
                SpannableString span = new SpannableString("当前家庭成员：" + userinfo.getCUSTOMERNAME());
                ForegroundColorSpan color = new ForegroundColorSpan(this.getResources().getColor(R.color.name_color));
                span.setSpan(color, 7, i, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                tv_name.setText(span);
                // tv_name.setText("当前家庭成员：" + userinfo.getCUSTOMERNAME());
            }

            menuAdapter = new MainMenuGridAdapter_Tj_JTYS(getApplicationContext());
            gd_menu.setAdapter(menuAdapter);
            img_back = (ImageView) findViewById(R.id.img_back);

            btn_jktj = (Button) findViewById(R.id.btn_jktj);

            jtys_list_img = (ImageView) findViewById(R.id.iv_photo);
            jtys_list_name = (TextView) findViewById(R.id.jtys_list_name);
            jtys_list_age = (TextView) findViewById(R.id.jtys_list_age);
            jtys_jdys_name = (TextView) findViewById(R.id.jtys_jdys_name);
            jtys_list_sex = (TextView) findViewById(R.id.jtys_list_sex);
            jtys_list_phone = (TextView) findViewById(R.id.jtys_list_phone);
            jtys_list_zdrq = (LabelsView) findViewById(R.id.jtys_list_zdrq);
            jtys_list_address = (TextView) findViewById(R.id.jtys_list_address);
//            jtys_list_state_sign = (ImageView) findViewById(R.id.jtys_list_state_sign);
//            jtys_list_state_unsign = (ImageView) findViewById(R.id.jtys_list_state_unsign);
            jtys_list_sfry = (LabelsView) findViewById(R.id.jtys_list_zdrq1);

            ll_wxsf = (LinearLayout) findViewById(R.id.ll_wxsf);
            img_patientsign=findViewById(R.id.img_patientsign);
            qianMing=findViewById(R.id.btn_sign);
            qianMing.setOnClickListener(this);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        modifyDisease();
        String ss= Environment.getExternalStorageDirectory() + "/PublicHealth/Sign/" + userinfo.getIDCARD() + ".png";
        setSign(ss,img_patientsign);
//        modifySignState();
    }

    /**
     * 修改疾病类型
     */
    public void modifyDisease() {
        ARCHIVE_BASEINFO userinfo1 = NovaApplication.getUserInfo();
        PopData.setPopInfo(jtys_list_zdrq, userinfo1, PopData.TAG_NORMAL, MainActivity_Menu_Tj.this);
        PopData.setPopInfo(jtys_list_sfry, userinfo1, PopData.TAG_WARNING, MainActivity_Menu_Tj.this);

        //判断是否是一般人群（一般人群，无需随访）
        if (!TextUtils.isEmpty(userinfo1.getPOPULATION_TYPE())) {
            String pop = userinfo1.getPOPULATION_TYPE();
            String[] pops = pop.split(",");

            for (String str : pops) {
                if (!TextUtils.isEmpty(str)) {
                    if (PeopleType.YBRQ.equals(str)) {
                        setIsShowWxSf(true);
                    } else {
                        setIsShowWxSf(false);
                    }
                }
            }
        }

    }

    /**
     * 设置随访是否显示
     *
     * @author 王婷婷
     * @date 2018年3月5日 下午4:09:16
     */
    private void setIsShowWxSf(boolean flag) {
        if (flag) {
            jtys_list_sfry.setVisibility(View.GONE);
            ll_wxsf.setVisibility(View.VISIBLE);
        } else {
            ll_wxsf.setVisibility(View.GONE);
            jtys_list_sfry.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 修改签约状态
     */
//    public void modifySignState() {
//
//        List<ARCHIVE_BASEINFO> idCardList = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,
//                "IDCARD = '" + userinfo.getIDCARD() + "'");
//        ARCHIVE_BASEINFO userinfo11 = idCardList.get(0);
//        userinfo11.setDISTRICT_ID(userinfo.getDISTRICT_ID());
//        userinfo11.setIS_UPDATE("Y");
//        NovaApplication.fdbmanger.updata(userinfo11);
//        userinfo = userinfo11;
//        NovaApplication.setUserInfo(userinfo);
//
//        if (TextUtils.isEmpty(userinfo.getDISTRICT_ID())) {
//            jtys_list_state_sign.setVisibility(View.GONE);
//            jtys_list_state_unsign.setVisibility(View.VISIBLE);
//        } else {
//            jtys_list_state_sign.setVisibility(View.VISIBLE);
//            jtys_list_state_unsign.setVisibility(View.GONE);
//        }
//
//    }

    @Override
    public void setListeners() {
        try {
            img_back.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // ActivityManager.finishAll();
                    // System.exit(0);
                    finish();
                }
            });
            btn_jktj.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(getApplicationContext(), MainActivity_Menu_NewTJ.class);
                    startActivity(intent);
                }
            });
            // 菜单选项
            gd_menu.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // 0 "个人档案",
                    // 1 "健康体检",
                    // 2 "重点人群",
                    // 3 "综合统计",
                    // 4 "打印条码",
                    // 5 "打印体检回执"
                    // 6 "拍取照片"
                    Intent intent = null;
                    if (position == 0) {
                        // 0 "个人档案",
                        intent = new Intent(getApplicationContext(), PersonalFileActivity.class);
                    } else if (position == 1) {
                        // 1 "健康体检",
//                        intent = new Intent(getApplicationContext(), TiJianActivity.class);
                        // 2 "重点人群",
//                        intent = new Intent(getApplicationContext(), FocusGroupMainActivity.class);
                        intent = new Intent(getApplicationContext(), GXYActivity.class);
                    } else if (position == 2) {
                        intent = new Intent(getApplicationContext(), TNBActivity.class);
//                        intent = new Intent(getApplicationContext(), ShowJieLunPicActivity.class);
                    } /*
                         * else if (position == 3) { // 3 健康教育 intent = new
						 * Intent(getApplicationContext(),
						 * JKJYMainActivity.class); } else if (position == 4) {
						 * // 4 打印条码 // intent = new
						 * Intent(getApplicationContext(), PrintActivity.class);
						 * Toast.makeText(getApplicationContext(), "该功能暂未启用",
						 * Toast.LENGTH_SHORT).show(); return; }
						 */ else if (position == 3) {
//                        intent = new Intent(getApplicationContext(), ShowJieLunPicActivity.class);
                        intent = new Intent(MainActivity_Menu_Tj.this, SBCLActivity.class);

                    }
                    // else if (position == 4) {
                    // // 5拍取照片
                    // intent = new Intent(getApplicationContext(),
                    // PhotoMainActivity2.class);
                    // }
					/*
					 * else if (position == 6) { // 6打印体检回执 intent = new
					 * Intent(getApplicationContext(),
					 * FocusGroupMainActivity.class); }
					 */
//                    else if (position == 4) {
                        // 7设备测量
                        // if(NovaApplication.idCardTool!=null){
                        // NovaApplication.idCardTool.closeAndExit();//TODO
                        // 关闭身份证读卡器tool
                        // }

//                        intent = new Intent(MainActivity_Menu_Tj.this, SBCLActivity.class);
						/*
						 * Intent intent3=new
						 * Intent(getApplicationContext(),NoticeService.class);
						 * stopService(intent3);
						 */

                        // if (NovaApplication.bloothTool != null) {
                        // NovaApplication.bloothTool.scanLeDevice(false);
                        // }

//                    }
//                    else if (position == 5) {
//                        // 家庭签约医生
//                        intent = new Intent(MainActivity_Menu_Tj.this, QYInfo.class);
//                    } else if (position == 6) {
//                        // //满意度评价
//                         intent = new Intent(MainActivity_Menu_Tj.this,
//                         DataDownLoadActivity.class);
//
//                    }
                    if(intent!=null){
                        startActivity(intent);
                    }

                }
            });
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        finish();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // if (NovaApplication.bloothTool != null) {
        // NovaApplication.bloothTool.closeAndExit();
        // }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_sign:
                Intent intent = new Intent(MainActivity_Menu_Tj.this, QianMingActivity.class);
                // //命名规则： 身份证号_签约时间_用户类型_创建时间时分秒_随机数.png[用户类型： 1 医生 2 患者 3
                // 其他图片]
                intent.putExtra(QianMingActivity.SIGNNAME_HEAD, getPhotoPath("2"));
                startActivityForResult(intent, REQUEST_CODE_PATIENT);
                break;
        }


    }   SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

    /**
     * 客户身份证号_签约时间_用户类型_创建时间时分秒_随机数.png
     * <p>
     * 370883198806046521_2017-12-07_1_20171207104138_8140.png
     *
     * @param type 1 医生 签名 2 患者签名 3 其他照片
     * @return
     * @author 鹿云龙
     * @date 2017年12月26日 上午10:13:28
     */
    private String getPhotoPath(String type) {
        if (type == null) {
            return null;
        }
        String str = "";
        File file = null;
        switch (type) {
            case "1":
            case "2":
                file = new File(Environment.getExternalStorageDirectory() + "/PublicHealth/Sign/");
                str = Environment.getExternalStorageDirectory() + "/PublicHealth/Sign/" + userinfo.getIDCARD() + ".png";

                break;
            case "3":
                file = new File(Environment.getExternalStorageDirectory() + "/PublicHealth/images/");
                str = Environment.getExternalStorageDirectory() + "/PublicHealth/images/" + userinfo.getIDCARD() + "_"
                        + type + "_" + sdf.format(new Date()) + "_"
                        + (int) ((Math.random() * 9 + 1) * 1000) + ".png";
                break;
            default:
                file = new File(Environment.getExternalStorageDirectory() + "/PublicHealth/images/");
                str = Environment.getExternalStorageDirectory() + "/PublicHealth/images/" + userinfo.getIDCARD() + "_"
                        + type + "_" + sdf.format(new Date()) + "_"
                        + (int) ((Math.random() * 9 + 1) * 1000) + ".png";
                break;
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        return str;
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
        super.onActivityResult(requestCode, resultCode, arg2);
        Log.e(TAG, "结果返回码：" + requestCode + "\n" + resultCode);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_PATIENT:
                    if (arg2.getExtras().containsKey("filePath")) {
                        strPatientSignPath = arg2.getExtras().getString("filePath");
                        setSign(strPatientSignPath, img_patientsign);
                        qianMing.setText("重签");
                    }
                    break;

                default:
                    break;
            }
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setSign(String imgPath, ImageView v) {
        // String result = "";

        if (!TextUtils.isEmpty(imgPath)) {
            Log.e(TAG, "照片src：" + imgPath);
            File file = new File(imgPath);
            if (file.exists()) {
                // v.setbacImageBitmap(ImageTools.readBitmapAutoSize(imgPath));
                v.setVisibility(View.VISIBLE);
                v.setBackground(new BitmapDrawable(null, ImageTools.readBitmapAutoSize(imgPath)));
            } else {
                v.setImageBitmap(null);
            }
        }
    }

}
